package com.fengxu.springcloud.controller;

import com.fengxu.springcloud.entity.CommonResult;
import com.fengxu.springcloud.entity.Payment;
import com.netflix.discovery.DiscoveryClient;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
@Log4j2
@RequestMapping("/consumer")
public class OrderController {

    // 单机版才把地址写死
//    public static final String PAYMENT_URL = "http://127.0.0.1:8001";
    // 向eureka集群注册后可以直接服务名访问，此时应该写服务名
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;


    @PostMapping("/payment/create")
    public CommonResult create(Payment payment){
        log.info("消费者调用创建接口 --> " + payment);
      return restTemplate.postForObject(PAYMENT_URL + "/api/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/payment/find/{id}")
    public CommonResult findPaymentById(@PathVariable("id") Integer id){
        log.info("消费者调用查询接口 id--> " + id);
        return restTemplate.getForObject(PAYMENT_URL+"/api/payment/find/"+id,CommonResult.class);
    }

    @GetMapping("/payment/find2/{id}")
    public CommonResult findPaymentById2(@PathVariable("id") Integer id){
        log.info("消费者调用查询接口 id--> " + id);
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/api/payment/find/"+id, CommonResult.class);
        if(entity.getStatusCode().is2xxSuccessful()){
            log.info("响应头:{}",entity.getHeaders());
            return entity.getBody();
        } else {
            return new CommonResult(404,"执行失败");
        }
    }

    @GetMapping("/payment/zipkin")
    public String sleuthZipkin(){
        return restTemplate.getForObject(PAYMENT_URL + "/api/payment/zipkin", String.class);
    }
}
